package com.hoo.common.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用返回对象
 * {
 *     data: '（正确）响应数据',
 *     msg: '（错误）响应信息',
 *     code: '响应码， 默认 200 正常， -1 错误，其他可自定义'
 * }
 *
 * @author hank
 * @create 2020-06-28 下午6:30
 **/
public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public R() {
        put("code", 200);
    }

    public static R error() {
        return error(-1, "未知异常，请联系管理员");
    }

    public static R error(String msg) {
        return error(-1, msg);
    }

    public static R error(Serializable code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    /**
     * 异常返回结果
     * @param code
     * @param msg
     * @return
     */
    public R exception(Serializable code, String msg){
        R r = new R();
        if(code != null){
            r.put("code", code);
        }
        r.put("msg", msg);
        return r;
    }

    /**
     * 返回正常结果（标准格式）
     * {
     *     code: 0,
     *     data: Object
     * }
     * @param value
     * @return
     */
    public static R data(Object value){
        R r = new R();
        r.put("data", value);
        return r;
    }

    /**
     * 返回分页结果
     * @param page
     * @return
     */
    public static R page(Object page){
        R r = new R();
        r.put("page", page);
        return r;
    }

}
